<!-- src/views/OSSFileManager.vue -->
<template>
  <div class="oss-manager">
    <el-container>
      <el-aside width="300px" class="file-tree">
        <el-tree
          :data="treeData"
          :props="{ label: 'name' }"
          @node-click="handleNodeClick"
          :load="loadNode"
          lazy
        />
      </el-aside>
      <el-main>
        <div class="editor-container" v-if="currentFile">
          <div class="editor-header">
            <span>{{ currentFile.name }}</span>
            <div class="editor-actions">
              <el-button type="primary" size="small" @click="saveFile">保存</el-button>
              <el-button type="danger" size="small" @click="handleDelete">删除</el-button>
            </div>
          </div>
          <div ref="monacoContainer" class="monaco-editor"></div>
        </div>
        <el-empty v-else description="请选择文件" />
      </el-main>
    </el-container>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import * as monaco from 'monaco-editor';
import { ElMessage, ElMessageBox } from 'element-plus';
import { initOSSClient, listFiles, getFileContent, uploadFile, deleteFile } from '@/utils/oss';

export default {
  name: 'OSSFileManager',
  setup() {
    const treeData = ref([]);
    const currentFile = ref(null);
    const editor = ref(null);
    const monacoContainer = ref(null);

    // Initialize OSS client
    onMounted(() => {
      // TODO: Replace with your OSS configuration
      initOSSClient({
        region: 'your-region',
        accessKeyId: 'your-access-key-id',
        accessKeySecret: 'your-access-key-secret',
        bucket: 'your-bucket',
      });
      
      loadRootFiles();
      
      // Initialize Monaco editor
      if (monacoContainer.value) {
        editor.value = monaco.editor.create(monacoContainer.value, {
          language: 'javascript',
          theme: 'vs-dark',
          automaticLayout: true,
        });
      }
    });

    onBeforeUnmount(() => {
      if (editor.value) {
        editor.value.dispose();
      }
    });

    const loadRootFiles = async () => {
      try {
        const { directories, files } = await listFiles();
        treeData.value = [
          ...directories.map(dir => ({
            name: dir.replace(/\/$/, ''),
            isDirectory: true,
            children: [],
          })),
          ...files.map(file => ({
            name: file.name,
            isDirectory: false,
          })),
        ];
      } catch (error) {
        ElMessage.error('加载文件列表失败');
      }
    };

    const loadNode = async (node, resolve) => {
      if (!node.data.isDirectory) {
        resolve([]);
        return;
      }

      try {
        const prefix = node.data.name + '/';
        const { directories, files } = await listFiles(prefix);
        const children = [
          ...directories.map(dir => ({
            name: dir.replace(prefix, '').replace(/\/$/, ''),
            isDirectory: true,
            children: [],
          })),
          ...files.map(file => ({
            name: file.name.replace(prefix, ''),
            isDirectory: false,
          })),
        ];
        resolve(children);
      } catch (error) {
        ElMessage.error('加载目录失败');
        resolve([]);
      }
    };

    const handleNodeClick = async (data) => {
      if (data.isDirectory) return;

      try {
        const content = await getFileContent(data.name);
        currentFile.value = data;
        
        // Set language based on file extension
        const fileExtension = data.name.split('.').pop().toLowerCase();
        const languageMap = {
          js: 'javascript',
          json: 'json',
          xml: 'xml',
          html: 'html',
          css: 'css',
        };
        
        editor.value.setModel(monaco.editor.createModel(
          content,
          languageMap[fileExtension] || 'plaintext'
        ));
      } catch (error) {
        ElMessage.error('加载文件内容失败');
      }
    };

    const saveFile = async () => {
      if (!currentFile.value) return;

      try {
        const content = editor.value.getValue();
        await uploadFile(currentFile.value.name, content);
        ElMessage.success('保存成功');
      } catch (error) {
        ElMessage.error('保存失败');
      }
    };

    const handleDelete = async () => {
      if (!currentFile.value) return;

      try {
        await ElMessageBox.confirm('确定要删除该文件吗？', '提示', {
          type: 'warning',
        });
        
        await deleteFile(currentFile.value.name);
        currentFile.value = null;
        editor.value.setValue('');
        await loadRootFiles();
        ElMessage.success('删除成功');
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败');
        }
      }
    };

    return {
      treeData,
      currentFile,
      monacoContainer,
      handleNodeClick,
      loadNode,
      saveFile,
      handleDelete,
    };
  },
};
</script>

<style scoped>
.oss-manager {
  height: 100%;
  padding: 20px;
}

.el-container {
  height: 100%;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
}

.file-tree {
  border-right: 1px solid #e6e6e6;
  padding: 20px;
}

.editor-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.editor-header {
  padding: 10px;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.monaco-editor {
  flex: 1;
  min-height: 500px;
}

.editor-actions {
  display: flex;
  gap: 10px;
}
</style> 